package org.dromara.system.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.lang.Pair;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import org.dromara.common.excel.utils.ConvertUtil;
import org.dromara.system.domain.vo.SysConfigVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springdoc.core.annotations.ParameterObject;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.SysI18nConfigVo;
import org.dromara.system.domain.bo.SysI18nConfigBo;
import org.dromara.system.service.ISysI18nConfigService;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 国际化配置
 *
 * @author yilong.fu
 * @date 2024-11-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/system/i18nConfig")
public class SysI18nConfigController extends BaseController {

    private final ISysI18nConfigService sysI18nConfigService;

    private final ISysOssService ossService;

    /**
     * 查询国际化配置列表
     */
    @SaCheckPermission("system:i18nConfig:list")
    @GetMapping("/list")
    public TableDataInfo<SysI18nConfigVo> list(@ParameterObject SysI18nConfigBo bo, @ParameterObject PageQuery pageQuery) {
        return sysI18nConfigService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询国际化配置列表
     */
    @GetMapping("/all/{lang}/{type}")
    public R<List<Pair<String, String>>> all(@PathVariable String lang, @PathVariable String type) {
        List<SysI18nConfigVo> list = sysI18nConfigService.queryList(new SysI18nConfigBo().builder()
            .language(lang.toLowerCase())
            .type(type).build());

        List<Pair<String, String>> result = new ArrayList<>();
        list.forEach(sysI18nConfigVo -> {
            result.add(Pair.of(sysI18nConfigVo.getEnCode(), sysI18nConfigVo.getContent()));
        });

        return R.ok(result);
    }

    /**
     * 导出国际化配置列表
     */
    @SaCheckPermission("system:i18nConfig:export")
    @Log(title = "国际化配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@ParameterObject SysI18nConfigBo bo, HttpServletResponse response) {
        List<SysI18nConfigVo> list = sysI18nConfigService.queryList(bo);
        ExcelUtil.exportExcel(list, "国际化配置", SysI18nConfigVo.class, response);
    }

    /**
     * 获取国际化配置详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:i18nConfig:query")
    @GetMapping("/{id}")
    public R<SysI18nConfigVo> getInfo(@NotNull(message = "主键不能为空")
                                      @PathVariable Long id) {
        return R.ok(sysI18nConfigService.queryById(id));
    }

    /**
     * 新增国际化配置
     */
    @SaCheckPermission("system:i18nConfig:add")
    @Log(title = "国际化配置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Long> add(@Validated(AddGroup.class) @RequestBody SysI18nConfigBo bo) {
        boolean flag = sysI18nConfigService.insertByBo(bo);
        if (!flag) {
            return R.fail();
        }
        return R.ok(bo.getId());
    }

    /**
     * 修改国际化配置
     */
    @SaCheckPermission("system:i18nConfig:edit")
    @Log(title = "国际化配置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysI18nConfigBo bo) {
        return toAjax(sysI18nConfigService.updateByBo(bo));
    }

    /**
     * 删除国际化配置
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:i18nConfig:remove")
    @Log(title = "国际化配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysI18nConfigService.deleteWithValidByIds(List.of(ids), true));
    }

    @PostMapping("/getImportTemplate")
    @Operation(summary = "获得导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<SysI18nConfigVo> list = Arrays.asList();
        // 输出
        ExcelUtil.write(response, "导入模板", "信息列表",
            SysI18nConfigVo.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入动态修改规则基本信息")
    @Parameters({@Parameter(name = "file", description = "Excel 文件", required = true), @Parameter(name = "mode", description = "导入模式1更新2追加3覆盖", example = "1"),
        @Parameter(name = "updatePart", description = "部分更新，默认为 true", example = "true")})
    @SaCheckPermission("system:i18nConfig:add")
    public R<Map<String, Object>> importExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam(value = "mode") Integer mode,
                                              @RequestParam(value = "updatePart", required = false, defaultValue = "false") Boolean updatePart) throws Exception {
        List<SysI18nConfigVo> list = ExcelUtil.read(file, SysI18nConfigVo.class);
        ConvertUtil<SysI18nConfigVo> convertUtil = new ConvertUtil<>(SysI18nConfigVo.class);
        List<SysI18nConfigVo> dynamicRuleCreateReqVOList = convertUtil.invoke(list).getDataList();
        List<SysI18nConfigVo> errorList = sysI18nConfigService.importList(dynamicRuleCreateReqVOList, mode, updatePart);

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("errorCount", errorList.size());
        if (!errorList.isEmpty()) {
            String fileName = "导入错误数据" + LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) + ".xlsx";
            ByteArrayOutputStream outputStream = ExcelUtil.writeStream("错误列表", errorList);
            SysOssVo sysOssVo = ossService.upload(outputStream, fileName);
            returnMap.put("errorFile", sysOssVo.getUrl());
        }

        return R.ok(returnMap);
    }
}
